<template>
  <div class="query">
    <div class="query__header flex">
      <span>Here is the query result:</span>
    </div>
    <div class="query__body relative flex flex-col">
      <div class="query__body-action flex items-center justify-end">
        <el-select v-model="model"
                   size="mini">
          <el-option label="Grid"
                     value="Grid"></el-option>
          <el-option label="Chart"
                     value="Chart"></el-option>
        </el-select>
      </div>
      <transition name="fade"
                  mode="out-in"
                  appear>
        <el-table :data="dataset"
                  :max-height="300"
                  border
                  v-if="model === 'Grid'">
          <el-table-column v-for="(key) in columns"
                           show-overflow-tooltip
                           :key="key"
                           :prop="key"
                           :label="key"></el-table-column>
        </el-table>

        <Chart v-else
               :view="view"
               class="flex-1"
               :dataset="dataset" />
      </transition>

    </div>

    <div class="query__footer">
      <el-button size="mini"
                 :disabled="$store.state.ai.loading"
                 @click.stop="onEdit">Edit in Widget Builder</el-button>
      <el-button size="mini"
                 :disabled="$store.state.ai.loading"
                 @click.stop="onAdd">Add to a Dashboard</el-button>
    </div>

    <WidgetBuilder :showSetting="builderVisible"
                   :dataInfo="modelInfo"
                   :selectFields="selectFields"
                   @queryModelClosed="onCloseBuilder"
                   :updateGadget="upgradeGadgetSetting"
                   ref="model" />

    <BWidgetModal :visible.sync="dashboardVisible"
                  :searchForm="searchForm"
                  :modelInfo="modelInfo" />
  </div>
</template>

<script>
import { v4 } from 'uuid'
import moment from 'moment'
import { cloneDeep, merge } from 'lodash'
import { updateQuery } from '@/api/new'
import { PAGE_SETTING } from '@/components/storybook/settings/page'


export default {
  name: 'Query',
  inheritAttrs: false,
  components: {
    BWidgetModal: () => import('@/components/storybook/b-widget-modal/index.vue'),
    WidgetBuilder: () => import('@/components/gadget/query-model/query-model'),
    Chart: () => import('../chart/gadget.vue')
  },

  props: {
    view: {
      type: Object,
      default: () => ({})
    },
    query: {
      type: Object,
      default: () => ({})
    },
    dataset: {
      type: Array,
      default: () => ([])
    },

    defaultModel: {
      type: String,
      default: 'Chart'
    }
  },
  data () {
    return {
      model: this.defaultModel === 'Grid' ? 'Grid' : this.view.name,

      builderVisible: false,
      dashboardVisible: false,

      searchForm: {
        name: '',
        resourceType: 0,
        layoutType: 'report_layout',
        orderField: '',
        order: [{ sort: 'DESC', field: 'update_date' }],
        filter: {
          type: ['Custom']
        },
        integration: {
          showAllIntegration: false,
          integrationGroup: []
        },
        pagination: merge(cloneDeep(PAGE_SETTING), {
          total: 0,
          pageSize: 10
        })
      },

      selectFields: [],
      modelInfo: {
        name: 'widget_' +
          moment().utc().format('YY/MM/DD HH:mm') +
          '_' +
          this._.random(1000, 9999, false),
        gadgetId: v4(),
        gadgetType: "AIChartGadget",
        gadgetSetting: this.view,
        businessType: "Custom",
        content: "select * from undefined",
        type: 1,
        language: 4,
        resourceType: 1,
        reuse: true,
        status: "Requested",
        tenantCode: this.$store.state.user.tenantCode,
        roleIdList: this.$store.state.defaultRoleList.concat(['1539094477886771202', '1603251831365554178'])
      },
    }
  },
  computed: {
    columns () {
      return this.dataset.length ? Object.keys(this.dataset[0]) : []
    },
  },
  methods: {

    async onCloseBuilder () {
      this.builderVisible = false
    },
    async createWidget () {
      const modelInfo = {
        ...this.modelInfo
      }
      const { data: response1 } = await this.$interface.reports.postReportSetting(modelInfo)

      if (response1.code !== 0) {
        throw response1.msg
      }
      const { datasetId, id, content, tenantCode, type } = this.query
      const { gadgetId, id: modelId } = response1.data || {}
      const querInfo = {
        datasetId,
        id,
        content,
        tenantCode,
        type,
        gadgetId,
        modelId
      }
      const { data: response2 } = await updateQuery(querInfo)

      if (response2.code !== 0) {
        throw response2.msg
      }

      return Object.assign({}, this.modelInfo, response1.data)
    },
    async onEdit () {
      try {
        this.$store.state.ai.loading = true

        this.modelInfo = await this.createWidget()

        this.builderVisible = true
      } catch (message) {
        this.$store.commit('SET_CONTENT',
          {
            type: 'GPT',
            name: "Message",
            options: {
              message
            }
          },
        )
      } finally {
        this.$store.state.ai.loading = false
      }
    },
    async onAdd () {
      try {
        this.$store.state.ai.loading = true

        this.modelInfo = await this.createWidget()

        this.dashboardVisible = true
      } catch (message) {
        this.$store.commit('SET_CONTENT',
          {
            type: 'GPT',
            name: "Message",
            options: {
              message
            }
          },
        )
      } finally {
        this.$store.state.ai.loading = false
      }

    },
    async onToggle () {
      this.model = this.model === 'Grid' ? this.view.name : 'Grid'
    },
    upgradeGadgetSetting (setting) {

    },
  }
}
</script>

<style lang="scss" scoped>
.query {
  &__header {
    margin-bottom: 8px;
    color: #333;
    font-weight: 500;
  }
  &__body {
    height: 350px;
    min-width: 450px;
    background: #ffffff;
    border: 1px solid rgba(0, 0, 0, 0.08);
    &-action {
      height: 48px;
      background: #f3f3f3;
      border-bottom: 1px solid rgba(0, 0, 0, 0.08);
      padding: 0 8px;
    }
  }
  &__footer {
    margin-top: 8px;
  }
}
</style>